//
//  OAuthViewController.swift
//  SinaWeibo
//
//  Created by 梁楠 on 16/1/13.
//  Copyright © 2016年 QQ主流框架. All rights reserved.
//

//登陆授权界面有BaseTable present出来的

import UIKit
import SVProgressHUD
import AFNetworking

class OAuthViewController: UIViewController {

    let webView = UIWebView()
    
    @objc private func defaultAccount () {
//    webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '13552421826'")
//        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('passwd').value = 'qishi521'")
        
        let jsString = "document.getElementById('userId').value = '13552421826',document.getElementById('passwd').value = 'qishi521'"
        
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    
    override func loadView() {
        
//        navigationController?.navigationBar.tintColor = UIColor.orangeColor()
        
        view = webView
        
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setNavBar()
        
        loadOAuthPage()
    }
    
    private func setNavBar () {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: UIBarButtonItemStyle.Plain, target: self, action: "defaultAccount")
        
    }
    
    private func loadOAuthPage () {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
    }
    
    
    @objc private func close () {
        
        dismissViewControllerAnimated(true, completion: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}

extension OAuthViewController : UIWebViewDelegate {
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //将URL转换成字符串
//        print(request.URL?.absoluteString)
        
        guard let urlString = request.URL?.absoluteString else {
            return false
        }
        
        if urlString.containsString("code=") {
            
            //query 将url中的参数获取到
            //port 端口号
            guard let query = request.URL?.query else {
                
                return false
            }
            
            let codeStr = "code="
            
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            print(code,query)
            
            loadAccessToken(code)
            
            return false
        }
        return true
    }
    
    private func loadAccessToken(code : String) {
        
        UserAccountViewModel().loadAccessToken(code) { (isSuccess) -> () in
            
            if !isSuccess {
                
                print("用户登录失败")
                SVProgressHUD.showErrorWithStatus("登录失败")
                
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("登录成功")
            
            self.dismissViewControllerAnimated(true, completion: { () -> Void in
                NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootVC, object: "Welcome")
                
//                print("通知")
            })
            
            
        }
    }
    
}
